export function dataURLtoFile(dataurl, filename) {
  //将base64转换为文件
  let arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, {
    type: mime
  })
}
/**
 *
 * @param {file,with,height,quality} { 文件，压缩后预期宽度，压缩后预期高度，文件质量0-1，越小越模糊}
 */
export function shrinKImage({
  file,
  width = 500,
  height = 500,
  quality = 0.6
}) {
  return new Promise((res, rej) => {
    let url = ''
    const reader = new FileReader()

    const img = new Image()

    const canvas = document.createElement('canvas'),
      cxt = canvas.getContext('2d')

    img.onload = function() {
      // 图片原始尺寸
      const originWidth = this.width
      const originHeight = this.height
      // 目标尺寸
      let targetWidth = originWidth,
        targetHeight = originHeight
      // 图片尺寸超过设定的限制
      if (originWidth > width || originHeight > height) {
        if (originWidth / originHeight > width / height) {
          // 更宽，按照宽度限定尺寸
          targetWidth = width
          targetHeight = Math.round(width * (originHeight / originWidth))
        } else {
          targetHeight = height
          targetWidth = Math.round(height * (originWidth / originHeight))
        }
      }

      // canvas对图片进行缩放
      canvas.width = targetWidth
      canvas.height = targetHeight
      // 清除画布
      cxt.clearRect(0, 0, targetWidth, targetHeight)
      // 图片压缩
      cxt.drawImage(img, 0, 0, targetWidth, targetHeight)

      url = canvas.toDataURL('image/png', quality)

      canvas.toBlob(function(blobFile) {
        res({ url, blobFile, width: targetWidth, height: targetHeight })
      })
    }

    //读取文件
    reader.readAsDataURL(file)

    reader.onload = function() {
      //base 64
      img.src = this.result
    }
    reader.onerror = function(error) {
      console.error('图片压缩出错-->', error)
      rej(false)
    }
  })
}
